#include "Uitem.h"
#include "HelloWorldScene.h"

Uitem::Uitem(void)
{
}


Uitem::~Uitem(void)
{
}


CCRect Uitem::rect()
{
    CCSize s = getTexture()->getContentSize();
    return CCRectMake(-s.width / 2, -s.height / 2, s.width, s.height);
}

Uitem* Uitem::uitemWithTexture(CCTexture2D* aTexture)
{
    Uitem* pUitem = new Uitem();
    pUitem->initWithTexture( aTexture );
    pUitem->autorelease();

    return pUitem;
}

bool Uitem::initWithTexture(CCTexture2D* aTexture)
{
    if( CCSprite::initWithTexture(aTexture) ) 
    {
        m_state = kUitemStateUngrabbed;
    }
    
    return true;
}

void Uitem::onEnter()
{
    CCDirector* pDirector = CCDirector::sharedDirector();
    pDirector->getTouchDispatcher()->addTargetedDelegate(this, 0, true);
    CCSprite::onEnter();
}

void Uitem::onExit()
{
    CCDirector* pDirector = CCDirector::sharedDirector();
    pDirector->getTouchDispatcher()->removeDelegate(this);
    CCSprite::onExit();
}    

bool Uitem::containsTouchLocation(CCTouch* touch)
{
    return rect().containsPoint(convertTouchToNodeSpaceAR(touch));
}

bool Uitem::ccTouchBegan(CCTouch* touch, CCEvent* event)
{
    if (m_state != kUitemStateUngrabbed) return false;
    if ( !containsTouchLocation(touch) ) return false;
    
    m_state = kUitemStateGrabbed;
    return true;
}

void Uitem::ccTouchMoved(CCTouch* touch, CCEvent* event)
{
    // If it weren't for the TouchDispatcher, you would need to keep a reference
    // to the touch from touchBegan and check that the current touch is the same
    // as that one.
    // Actually, it would be even more complicated since in the Cocos dispatcher
    // you get CCSets instead of 1 UITouch, so you'd need to loop through the set
    // in each touchXXX method.
	 CCPoint touchPoint = touch->getLocation();
	CCLOG("CCPoint: %s %f %s %f \n", "x:", touchPoint.x, "y:", touchPoint.y);
    
    CCAssert(m_state == kUitemStateGrabbed, "Uitem - Unexpected state!");    
    
   
    
    setPosition( ccp(touchPoint.x, touchPoint.y) );

	if(touchPoint.x>231 && touchPoint.x<241 && touchPoint.y > 113 && touchPoint.y<125){
		CCActionInterval*  action2 = CCFadeOut::create(1.0f);
		tooth->runAction(action2);
	}
		 
}

CCObject* Uitem::copyWithZone(CCZone *pZone)
{
    this->retain();
    return this;
}

void Uitem::ccTouchEnded(CCTouch* touch, CCEvent* event)
{
    CCAssert(m_state == kUitemStateGrabbed, "Uitem - Unexpected state!");    
    
	setPosition(ccp(210,45));

    m_state = kUitemStateUngrabbed;
} 

void Uitem::touchDelegateRetain()
{
    this->retain();
}

void Uitem::touchDelegateRelease()
{
    this->release();
}

void Uitem::setTooth(CCSprite* tooth){
	this->tooth = tooth;
}